﻿using DeepEarth.Map.Core;
using DeepEarth.Core;
using System.Windows;
using System;
namespace DeepEarth.Toolkit.Geometry.Clipping
{
    public static class Utilities
    {
        static bool FindWrapPoint(IMap map, out double wrapPoint)
        {
            // note: is the cutoff ever less than 0?
            wrapPoint = -180;

            double leftWest = 0;
            double leftEast = 90;
            double rightWest = 90;
            double rightEast = 180;

            bool wrapExists = false;

            while (true)
            {
                if (rightWest == rightEast)
                {
                    wrapPoint = leftWest;
                    break;
                }

                double left = map.LocationToViewportPoint(new Location(0, rightWest)).X;
                double right = map.LocationToViewportPoint(new Location(0, rightEast)).X;

                if (left > right)
                {
                    wrapExists = true;
                    double mid = (rightWest + rightEast) / 2;
                    // precision
                    if (mid == rightWest || mid == rightEast)
                    {
                        wrapPoint = mid;
                        break;
                    }

                    leftWest = rightWest;
                    leftEast = mid;
                    rightWest = mid;
                }
                else
                {
                    left = map.LocationToViewportPoint(new Location(0, leftWest)).X;
                    right = map.LocationToViewportPoint(new Location(0, leftEast)).X;

                    if (left > right)
                    {
                        wrapExists = true;
                        double mid = (leftWest + leftEast) / 2;

                        // precision
                        if (mid == leftWest || mid == leftEast)
                        {
                            wrapPoint = mid;
                            break;
                        }

                        rightWest = mid;
                        rightEast = leftEast;
                        leftEast = mid;
                    }
                    else
                    {
                        wrapPoint = leftWest;
                        break;
                    }
                }
            }

            if (!wrapExists)
            {
                wrapPoint = -180;
                return false;
            }
            else
            {
                return true;
            }

        }
    }
}
